﻿using Ozone.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ozone.BLL
{
    /// <summary>
    /// 设备初始化  以及设备准备工作
    /// </summary>
    public class DeviceInitBLL
    {
        /// <summary>
        /// 设备初始化
        /// </summary>
        /// <returns></returns>
        public static bool InitDevice()
        {
            bool IsSuccess = false;
            try
            {
                //发送设备初始化指令
                Thread.Sleep(100);
                //监控设备初始化状态

                Task.Run(() => RadisService.SetKeyValueAsync("AGVRebotConnectState", "0")).GetAwaiter().GetResult();





                //返回结果

            }
            catch (Exception)
            {

                IsSuccess = false;
            }

            IsSuccess = true;
            return IsSuccess;
        }


        /// <summary>
        /// 异步初始化设备并监控连接状态
        /// </summary>
        /// <param name="timeoutMs">超时时间（毫秒，默认30秒）</param>
        /// <returns>初始化结果</returns>
        public static async Task<bool> InitDeviceAsync()
        {
            try
            {
                // 1. 发送初始化指令
                await Task.Delay(100); // 模拟指令发送延迟

                // 2. 设置初始状态
                await RadisService.SetKeyValueAsync("DeviceInit", "Init");
                // 3. 监控设备连接状态（等待状态变为"1"表示成功）
                var (isSuccess, message) = await RadisService.MonitorKeyValueAsync(
                    monitorKey: "DeviceInit",
                    targetValue: "ExecSuccess", // 假设"ExecSuccess"表示连接成功
                    intervalMs: 500,  // 每500ms检查一次
                    timeoutMs: 30000);

                if (!isSuccess)
                {
                    //Console.WriteLine($"设备初始化失败: {message}");
                    return false;
                }
                else
                {
                    //Console.WriteLine($"设备初始化失败: {message}");
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"设备初始化异常: {ex.Message}");
                return false;
            }
        }


    }
}
